package com.blog.cloud.auth.oauth.request;

import com.alibaba.fastjson.JSONObject;
import com.blog.cloud.auth.oauth.cache.AuthDefaultSource;
import com.blog.cloud.auth.oauth.cache.AuthStateCache;
import com.blog.cloud.auth.oauth.config.AuthConfig;
import com.blog.cloud.auth.oauth.enums.AuthResponseStatus;
import com.blog.cloud.auth.oauth.enums.AuthUserGender;
import com.blog.cloud.auth.oauth.exception.AuthException;
import com.blog.cloud.auth.oauth.model.AuthCallback;
import com.blog.cloud.auth.oauth.model.AuthResponse;
import com.blog.cloud.auth.oauth.model.AuthToken;
import com.blog.cloud.auth.oauth.model.AuthUser;
import me.zhyd.oauth.utils.AuthScopeUtils;
import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

public class AuthQqRequest extends AuthDefaultRequest {
    public AuthQqRequest(AuthConfig config) {
        super(config, AuthDefaultSource.QQ);
    }

    public AuthQqRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, AuthDefaultSource.QQ, authStateCache);
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        String response = this.doGetAuthorizationCode(authCallback.getCode());
        return this.getAuthToken(response);
    }

    @Override
    public AuthResponse refresh(AuthToken authToken) {
        String response = (new HttpUtils(this.config.getHttpConfig())).get(this.refreshTokenUrl(authToken.getRefreshToken()));
        return AuthResponse.builder()
                .code(AuthResponseStatus.SUCCESS.getCode())
                .data(this.getAuthToken(response))
                .build();
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String openId = this.getOpenId(authToken);
        String response = this.doGetUserInfo(authToken);
        JSONObject object = JSONObject.parseObject(response);
        if (object.getIntValue("ret") != 0) {
            throw new AuthException(object.getString("msg"));
        } else {
            String avatar = object.getString("figureurl_qq_2");
            if (StringUtils.isEmpty(avatar)) {
                avatar = object.getString("figureurl_qq_1");
            }

            String location = String.format("%s-%s", object.getString("province"), object.getString("city"));
            return AuthUser.builder()
                    .rawUserInfo(object)
                    .username(object.getString("nickname"))
                    .nickname(object.getString("nickname"))
                    .avatar(avatar)
                    .location(location)
                    .uuid(openId)
                    .gender(AuthUserGender.getRealGender(object.getString("gender")))
                    .token(authToken)
                    .source(this.source.toString())
                    .build();
        }
    }

    @Override
    public String authorize(String state) {
        return UrlBuilder.fromBaseUrl(super.authorize(state)).queryParam("scope", this.getScopes(",", false, AuthScopeUtils.getDefaultScopes(AuthQqScope.values()))).build();
    }

    private String getOpenId(AuthToken authToken) {
        String response = (new HttpUtils(this.config.getHttpConfig())).get(UrlBuilder.fromBaseUrl("https://graph.qq.com/oauth2.0/me").queryParam("access_token", authToken.getAccessToken()).queryParam("unionid", this.config.isUnionId() ? 1 : 0).build());
        String removePrefix = response.replace("callback(", "");
        String removeSuffix = removePrefix.replace(");", "");
        String openId = removeSuffix.trim();
        JSONObject object = JSONObject.parseObject(openId);
        if (object.containsKey("error")) {
            throw new AuthException(object.get("error") + ":" + object.get("error_description"));
        } else {
            authToken.setOpenId(object.getString("openid"));
            if (object.containsKey("unionid")) {
                authToken.setUnionId(object.getString("unionid"));
            }

            return StringUtils.isEmpty(authToken.getUnionId()) ? authToken.getOpenId() : authToken.getUnionId();
        }
    }

    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilder.fromBaseUrl(this.source.userInfo()).queryParam("access_token", authToken.getAccessToken()).queryParam("oauth_consumer_key", this.config.getClientId()).queryParam("openid", authToken.getOpenId()).build();
    }

    private AuthToken getAuthToken(String response) {
        Map<String, String> accessTokenObject = GlobalAuthUtils.parseStringToMap(response);
        if (accessTokenObject.containsKey("access_token") && !accessTokenObject.containsKey("code")) {
            return AuthToken.builder()
                    .accessToken((String)accessTokenObject.get("access_token"))
                    .expireIn(Integer.parseInt((String)accessTokenObject.getOrDefault("expires_in", "0")))
                    .refreshToken((String)accessTokenObject.get("refresh_token"))
                    .build();
        } else {
            throw new AuthException((String)accessTokenObject.get("msg"));
        }
    }

}
